package com.teamin.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.teamin.entity.WxUserEntity;
import com.teamin.security.AESUtils;
import com.teamin.service.JwtService;
import com.teamin.service.UserService;
import com.teamin.web.exception.GlobalErrorInfoException;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 用来接口回调的接口,不需要验证登录状态
 *
 * @author qfu
 * @date 2017/9/25
 *
 */
@RestController
@RequestMapping("/v1/callback")
@Api(basePath = "/v1/callback",description = "提供给 第三方调用 ,无登录验证,只做数据验证",tags = "回调")
public class CallBackController extends  BaseController{

	// 微信关注公众号后回调后对参数的解密密钥
	public static final String TEAMIN_ENCODE_KEY = "1K8LkMYdrtLZ6hio";
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	PodamFactory factory = new PodamFactoryImpl();
	@Autowired
	private JwtService jwtService;
	@Autowired
	private UserService userService;

	/**
	 * 公众号被关注的回调
	 * @throws GlobalErrorInfoException
	 */
	@RequestMapping(value = "/wxmpsubscript", method = RequestMethod.POST)
	public void WxSubscript(HttpServletRequest request)throws GlobalErrorInfoException, IOException {
		logger.info("WxSubscript" );
		JSONObject jsobject = JSONObject.parseObject(AESUtils.decrypt(getInputData(request.getInputStream()), TEAMIN_ENCODE_KEY));

		logger.debug("WxSubscript = "+ jsobject);
		if(jsobject != null && "subscribe".equals(jsobject.getString("event"))) {//关注公众号事件
			WxUserEntity we = new WxUserEntity();
			we.setUnionId(jsobject.getString("unionid"));
			we.setAvatarUrl(jsobject.getString("headimgurl"));
			we.setLanguage(jsobject.getString("language"));
			we.setMpOpenId(jsobject.getString("openid"));
			we.setNickName(jsobject.getString("nickname"));
			userService.saveOrUpdateWxUser(we);
		}else if(jsobject != null && "unsubscribe".equals(jsobject.getString("event"))) {//取消关注公众号事件
			userService.cancleMPAttention(jsobject.getString("openid")) ;
		}
	}
}